package com.wang.springbootinit.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wang.springbootinit.common.ErrorCode;
import com.wang.springbootinit.constant.BISystemEnum;
import com.wang.springbootinit.exception.BusinessException;
import com.wang.springbootinit.model.entity.ChatHistory;
import com.wang.springbootinit.model.entity.User;
import com.wang.springbootinit.model.param.AnswerOperateParam;
import com.wang.springbootinit.model.vo.AnswerVO;
import com.wang.springbootinit.service.AnswerService;
import com.wang.springbootinit.service.ChatHistoryService;
import com.wang.springbootinit.service.UserService;
import com.wang.springbootinit.sparkAi.AiAnalyseModel;
import com.wang.springbootinit.sparkAi.AiAnalyseQueryParam;
import com.wang.springbootinit.sparkAi.AnalyseService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.jdbc.object.SqlFunction;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * AI
 */
@Service
@Slf4j
public class AnswerServiceImpl implements AnswerService {
    @Resource
    private AnalyseService analyseService;
    @Resource
    private UserService userService;
    @Resource
    private ChatHistoryService chatHistoryService;

    /**
     * 普通答疑
     * @param answerOperateParam
     * @return
     */
    @Override
    public AnswerVO answerQuestion(AnswerOperateParam answerOperateParam, HttpServletRequest request) {
        if(StrUtil.isEmpty(answerOperateParam.getAnswerStr())){
            throw  new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        if (loginUser == null) {
            throw new BusinessException(BISystemEnum.NOLOGIN.getCode(), BISystemEnum.NOLOGIN.getMsg());
        }
        AnswerVO answerVO = new AnswerVO();

        AiAnalyseQueryParam aiAnalyseQueryParam = new AiAnalyseQueryParam();
        aiAnalyseQueryParam.setUserQuestionContent(answerOperateParam.getAnswerStr());
        try {
            AiAnalyseModel aiAnalyseModel = analyseService.simpleAnswerQuestion(aiAnalyseQueryParam);
            if(!aiAnalyseModel.getIsSuccess()){
                answerVO.setContent(aiAnalyseModel.getExceptionContent());
                return answerVO;
            }

            //存储聊天消息
            List<ChatHistory> chatHistoryList = getChatHistoryList(answerOperateParam, aiAnalyseModel, loginUser);
            chatHistoryService.saveChatHistories(chatHistoryList);

            String conversationId = chatHistoryList.get(0).getConversationId();
            answerVO.setContent(aiAnalyseModel.getContent());
            answerVO.setConversationId(conversationId);
            return answerVO;
        } catch (Exception e) {
            log.error("AnswerServiceImpl answerQuestion exception:",e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 获取聊天记录model
     * @param answerOperateParam
     * @param aiAnalyseModel
     * @param loginUser
     * @return
     */
    private List<ChatHistory> getChatHistoryList(AnswerOperateParam answerOperateParam,AiAnalyseModel aiAnalyseModel,User loginUser) {
        String conversationId = getRandomConversationId(answerOperateParam);
        int maxSort = getChatMaxSort(answerOperateParam);
        List<ChatHistory> chatHistories = new ArrayList<>();
        //提问
        ChatHistory chatHistoryUser = new ChatHistory();
        chatHistoryUser.setUserId(loginUser.getId());
        chatHistoryUser.setChatInfo(answerOperateParam.getAnswerStr());
        chatHistoryUser.setConversationId(conversationId);
        chatHistoryUser.setChatUserType("USER");
        chatHistoryUser.setSort(++maxSort);
        chatHistories.add(chatHistoryUser);

        //结果
        ChatHistory chatHistoryAI = new ChatHistory();
        if(aiAnalyseModel.getIsSuccess()){
            chatHistoryAI.setChatInfo(aiAnalyseModel.getContent());
        }else{
            chatHistoryAI.setChatInfo("此次回答出现异常，请重试");
        }
        chatHistoryAI.setUserId(loginUser.getId());
        chatHistoryAI.setConversationId(conversationId);
        chatHistoryAI.setChatUserType("AI");
        chatHistoryAI.setSort(++maxSort);
        chatHistories.add(chatHistoryAI);
        return chatHistories;
    }

    /**
     * 获取当前会话的最大sort
     * @param answerOperateParam
     * @return
     */
    private Integer getChatMaxSort(AnswerOperateParam answerOperateParam) {
        if(StrUtil.isEmpty(answerOperateParam.getConversationId())){
            return -1;
        }
        LambdaQueryWrapper<ChatHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ChatHistory::getConversationId,answerOperateParam.getConversationId());
        List<ChatHistory> list = chatHistoryService.list(queryWrapper);
        if(CollUtil.isEmpty(list)) {
            return -1;
        }
        return list.stream().map(ChatHistory::getSort).max(Integer::compareTo).get();
    }


    /**
     * 回去会话id
     * @return String
     */
    private String getRandomConversationId(AnswerOperateParam answerOperateParam){
        if(StrUtil.isEmpty(answerOperateParam.getConversationId())){
            return IdUtil.simpleUUID();
        }
        return answerOperateParam.getConversationId();
    }

}
